﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using MITI;

namespace MapControl.Misc.DAL
{
    public class GPSData
    {
        public int ID;
        public string Name;
        public DateTime LocalTime;
        public double LonGPS;
        public double LatGPS;
        public double Alt;
        public double Speed;
        public double Angle;
        public double Distance;
        public int Airport_Id;

        public GPSData(string name, DateTime local, double lon, double lat, double alt, double speed, double angle)
        {
            LocalTime = local;
            Name = name;
            LonGPS = lon;
            LatGPS = lat;
            Alt = alt;
            Speed = speed;
            Angle = angle;
        }

        /// <summary>
        /// Lấy dữ liệu nhận từ cổng COM chuyển thành đối tượng
        /// </summary>
        /// <param name="data"></param>
        public GPSData(string data)
        {
            string[] valueArray = data.Split(new char[1] { ',' });
            LocalTime = DateTime.Now;
            Name = valueArray[0];
            string sign;

            sign = valueArray[1].Substring(0, 1);
            double degree = double.Parse(valueArray[1].Substring(1, 2));
            double minute = double.Parse(valueArray[1].Substring(3));
            double lat = (minute / 60000f) + degree;
            LatGPS = GeneralClass.StringCoordToDecimalCoord(sign + lat.ToString("#.00000"));

            sign = valueArray[2].Substring(0, 1);
            degree = double.Parse(valueArray[2].Substring(1, 3));
            minute = double.Parse(valueArray[2].Substring(4));
            double lon = (minute / 60000f) + degree;
            LonGPS = GeneralClass.StringCoordToDecimalCoord(sign + lon.ToString("#.00000"));

            Alt = Double.Parse(valueArray[3]);
            Speed = Double.Parse(valueArray[4]);
            Angle = Double.Parse(valueArray[5]);
        }

        public GPSData(DataRow row)
        {
            LocalTime = DateTime.Parse(row["localtime"].ToString());
            Name = row["name"].ToString();
            LonGPS = double.Parse(row["lon"].ToString());
            LatGPS = double.Parse(row["lat"].ToString());
            Alt = double.Parse(row["alt"].ToString());
            Speed = double.Parse(row["speed"].ToString());
            Angle = double.Parse(row["angle"].ToString());
            Distance = double.Parse(row["distance"].ToString());
        }
        /// <summary>
        /// Convert instance to byte array
        /// </summary>
        /// <returns></returns>
        public char[] ConverToByteArray()
        {
            char[] data = new char[GeneralClass.DATA_LEN];
            char[] comma = new char[1] { ',' };
            char[] hemisphereOUmeridienLat;
            int index = 0;

            //name: 4 byte
            char[] nameArray = Name.ToCharArray(0, GeneralClass.NAME_LEN);
            nameArray.CopyTo(data, index);
            index += nameArray.Length;
            //Add comma
            comma.CopyTo(data, index);

            //lat: 8 byte
            index++;
            char[] latArray;
            double value = LatGPS;
            if (value > 0)
                hemisphereOUmeridienLat = new char[1] { 'N' };
            else
                hemisphereOUmeridienLat = new char[1] { 'S' };
            latArray = string.Format("{0}{1}", new string(hemisphereOUmeridienLat), Math.Abs(value).ToString("00.00000").Replace(".", "")).ToCharArray(0, GeneralClass.LAT_LEN);
            latArray.CopyTo(data, index);
            index += latArray.Length;
            //Add comma
            comma.CopyTo(data, index);

            //lon: 9 byte
            index++;
            char[] lonArray;
            value = LonGPS;
            if (LonGPS > 0)
                hemisphereOUmeridienLat = new char[1] { 'E' };
            else
                hemisphereOUmeridienLat = new char[1] { 'W' };
            lonArray = string.Format("{0}{1}", new string(hemisphereOUmeridienLat), Math.Abs(value).ToString("000.00000").Replace(".", "")).ToCharArray(0, GeneralClass.LON_LEN);
            lonArray.CopyTo(data, index);
            index += lonArray.Length;
            //Add comma
            comma.CopyTo(data, index);

            //alt: 4 byte
            index++;
            char[] altArray;
            value = Alt;
            if (value < 10)
                altArray = string.Format("000{0}", value.ToString()).ToCharArray(0, GeneralClass.ALT_LEN);
            else if (value < 100)
                altArray = string.Format("00{0}", value.ToString()).ToCharArray(0, GeneralClass.ALT_LEN);
            else if (value < 1000)
                altArray = string.Format("0{0}", value.ToString()).ToCharArray(0, GeneralClass.ALT_LEN);
            else if (value < 10000)
                altArray = string.Format("{0}", value.ToString()).ToCharArray(0, GeneralClass.ALT_LEN);
            else //error
                altArray = string.Format("-111").ToCharArray();
            altArray.CopyTo(data, index);
            index += altArray.Length;
            //Add comma
            comma.CopyTo(data, index);

            //speed: 3 byte
            index++;
            char[] speedArray;
            value = Speed;
            if (value < 10)
                speedArray = string.Format("00{0}", value.ToString()).ToCharArray(0, GeneralClass.SPEED_LEN);
            else if (value < 100)
                speedArray = string.Format("0{0}", value.ToString()).ToCharArray(0, GeneralClass.SPEED_LEN);
            else if (value < 1000)
                speedArray = string.Format("{0}", value.ToString()).ToCharArray(0, GeneralClass.SPEED_LEN);
            else //error
                speedArray = string.Format("-11").ToCharArray();
            speedArray.CopyTo(data, index);
            index += speedArray.Length;
            //Add comma
            comma.CopyTo(data, index);

            //angle: 3 byte
            index++;
            char[] angleArray;
            value = Angle;
            if (value < 10)
                angleArray = string.Format("00{0}", value.ToString()).ToCharArray(0, GeneralClass.ANGLE_LEN);
            else if (value < 100)
                angleArray = string.Format("0{0}", value.ToString()).ToCharArray(0, GeneralClass.ANGLE_LEN);
            else if (value < 1000)
                angleArray = string.Format("{0}", value.ToString()).ToCharArray(0, GeneralClass.ANGLE_LEN);
            else //error
                angleArray = string.Format("-11").ToCharArray();
            angleArray.CopyTo(data, index);

            return data;
        }

        public override bool Equals(System.Object obj)
        {
            // If parameter is null return false.
            if (obj == null)
            {
                return false;
            }

            // If parameter cannot be cast to Point return false.
            GPSData p = obj as GPSData;
            if ((System.Object)p == null)
            {
                return false;
            }
            
            // Return true if the fields match:
            return (LocalTime == p.LocalTime) && (LonGPS == p.LonGPS) && (LatGPS == p.LatGPS) && (Alt == p.Alt) && (Speed == p.Speed) && (Angle == p.Angle);
        }

        public bool Equals(GPSData p)
        {
            // If parameter is null return false:
            if ((object)p == null)
            {
                return false;
            }

            // Return true if the fields match:
            return (LocalTime == p.LocalTime) && (LonGPS == p.LonGPS) && (LatGPS == p.LatGPS) && (Alt == p.Alt) && (Speed == p.Speed) && (Angle == p.Angle);
        }
    }

    public static class GPSDataRepository
    {
        /// <summary>
        /// Lưu vào CSDL
        /// </summary>
        public static void Save(GPSData gps)
        {
            //Lưu vào CSDL
            string sql = string.Format("insert into gpsdata(localtime, name, lat, lon, alt, speed, angle, distance, airport_id) values ('{0}','{1}',{2},{3},{4},{5},{6},{7},{8})", gps.LocalTime, gps.Name, gps.LatGPS, gps.LonGPS, gps.Alt, gps.Speed, gps.Angle, gps.Distance, gps.Airport_Id);
            BaseDBCe.ExecSql_NoneQuery(sql);
        }

        public static DataTable LoadDatabase(int min, int max)
        {
            string sql;
            if (min == max && max == 0)
                sql = "select * from gpsdata";
            else
                sql = string.Format("select * from gpsdata where id >= {0} and id <= {1}", min, max);

            return BaseDBCe.ExecSql_DataSet(sql).Tables[0];
        }

        public static void DeleteAll()
        {
            string sql = "delete from gpsdata";
            BaseDBCe.ExecSql_NoneQuery(sql);
            sql = "ALTER TABLE gpsdata ALTER COLUMN [Id] IDENTITY (1,1)";
            BaseDBCe.ExecSql_NoneQuery(sql);
        }

        public static void UpdateDistance(int id, int distance)
        {
            string sql = string.Format("update gpsdata set distance = {0} where id = {1}", distance, id);
            BaseDBCe.ExecSql_NoneQuery(sql);
        }
    }

}
